package com.maddox.relax.view;

import android.app.ActionBar;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.maddox.relax.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 流式布局
 *
 * @author maddox
 */
public class MFlowLayout extends ViewGroup {
    //记录所有行的View列表
    private List<List<View>> mViews = new ArrayList<>();
    //记录所有行的各自最大高度
    private List<Integer> mLineHeight = new ArrayList<>();

    public MFlowLayout(Context context) {
        super(context);
    }

    public MFlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        //当前布局的最大宽度和高度
        int width = 0;
        int height = 0;
        //每一行子view的宽高
        int lineWidth = 0;
        int lineHeight = 0;
        int count = getChildCount();

        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() == GONE) {
                continue;
            }
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            //获取每个子View的宽度
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            //获取每个子View的高度
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;

            //如果当前子View与当前行的已使用宽度超出了父布局的宽度大小,则进入下一行
            if (lineWidth + childWidth > widthSize - getPaddingLeft() - getPaddingRight()) {
                //超出一行,先记录当前行的宽度,再去新建一行
                width = Math.max(width, lineWidth);
                //新的一行宽度等于当前子View的宽度
                lineWidth = childWidth;
                //记录行总高度
                height += lineHeight;
                //记录新一行的高度
                lineHeight = childHeight;
            } else {
                //如果没有换行,则累加当前子View的宽度到当前行宽度
                lineWidth += childWidth;
                //得到行子View的最大行高度
                lineHeight = Math.max(lineHeight, childHeight);
            }
             //处理最后一个子View的情况
            if (i == count - 1) {
                width = Math.max(lineWidth, width);
                height += lineHeight;
            }

            //设置父布局的大小
            setMeasuredDimension(
                    //当父布局的宽高为具体值时,就使用设置的具体值,否则使用子View的总体宽高
                    widthMode == MeasureSpec.EXACTLY ? widthSize : width + getPaddingLeft() + getPaddingRight(),
                    heightMode == MeasureSpec.EXACTLY ? heightSize : height + getPaddingTop() + getPaddingBottom()
            );


        }


    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        mViews.clear();
        mLineHeight.clear();
        //获取当前ViewGroup的宽度
        int width = getWidth();
        int lineWidth = 0;
        int lingHeight = 0;
        //记录当前行的View
        List<View> lineViews = new ArrayList<>();
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();
            if (childWidth + lineWidth + lp.leftMargin + lp.rightMargin > width - getPaddingLeft() - getPaddingRight()) {
                mLineHeight.add(lingHeight);
                mViews.add(lineViews);
                lineWidth = 0;
                lingHeight = childHeight + lp.topMargin + lp.bottomMargin;
                lineViews = new ArrayList<>();
            }
            lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
            lingHeight = Math.max(lingHeight, childHeight + lp.topMargin + lp.bottomMargin);
            lineViews.add(child);
        }
        //记录每行高度,为后面设置子View单独top做准备,比如 gravity
        mLineHeight.add(lingHeight);
        mViews.add(lineViews);

        int left = getPaddingLeft();
        int top = getPaddingTop();
        int lineCount = mViews.size();
        for (int i = 0; i < lineCount; i++) {
            lineViews = mViews.get(i);
            lingHeight=mLineHeight.get(i);
            int lineViewCount = lineViews.size();

            for (int j = 0; j < lineViewCount; j++) {
                View child = lineViews.get(j);
                if (child.getVisibility()==GONE){
                    continue;
                }
                MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
                int cLeft = left+lp.leftMargin;
                int cTop = top+lp.topMargin;
                int cRight = child.getMeasuredWidth()+cLeft;
                int cBottom = cTop+child.getMeasuredHeight();
                child.layout(cLeft,cTop,cRight,cBottom);
                left+=child.getMeasuredWidth()+lp.leftMargin+lp.rightMargin;


            }

            left=0;
            top+=lingHeight;
        }
    }

    /**
     *  设置填充数据
     * @param data
     */
    public void setData(List<String> data){
        if (data==null||data.size()<=0)
            return;
        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
        lp.leftMargin=5;
        lp.rightMargin=5;
        lp.topMargin=5;
        lp.bottomMargin=5;
        for (int i = 0; i < data.size(); i++) {
            TextView textView = new TextView(getContext());
            textView.setTextColor(randomColor());
            textView.setText(data.get(i));
            textView.setBackgroundResource(R.drawable.flow_item_bg);
            addView(textView,lp);
        }
    }

    private  int randomColor(){
        Random random = new Random();
        return Color.rgb(random.nextInt(256),random.nextInt(256),random.nextInt(256));
    }

    private OnItemClickListener clickListener;

    /**
     *  设置点击事件
     * @param clickListener 点击回调
     */
    public void setOnItemClickListener(OnItemClickListener clickListener) {
        if (clickListener==null)
            return;
        this.clickListener = clickListener;
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            int index = i;
            child.setOnClickListener(v->{
                this.clickListener.onItemClick(child,index);
            });
        }


    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(),attrs);
    }


    public static interface OnItemClickListener{
        void onItemClick(View itemView,int position);
    }

}
